package com.xingxing.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.xingxing.io.Resources;
import com.xingxing.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @program: IPersistence_test
 * @description:
 * @author: xinghaozhao
 * @create: 2020-08-21
 */
public class XMLConfigBuilder {
    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 该方法就是使用dom4j对配置文件进行解析，封装Configuration
     */
    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {

        Document document = new SAXReader().read(inputStream);

        //得到<configuration>根对象
        Element rootElement = document.getRootElement();
        List<Element> selectNodes = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        selectNodes.forEach(element -> properties.setProperty(element.attributeValue("name"), element.attributeValue("value")));

        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        configuration.setDataSource(comboPooledDataSource);

        //对mapper.xml进行解析：拿到路径后将mapper.xml加载成子节输入流 再使用dom4j进行解析
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        mapperList.forEach(element -> {
            String mapperPath = element.attributeValue("resource");
            InputStream resourceAsStream = Resources.getResourceAsStream(mapperPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            try {
                xmlMapperBuilder.parse(resourceAsStream);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
        });

        return configuration;
    }
}
